package main

import (
	"context"
	"time"

	"github.com/influxdata/influxdb-client-go/v2"
	"github.com/influxdata/influxdb-client-go/v2/api/query"
	"github.com/influxdata/influxdb-client-go/v2/api/write"
)

type InfluxDB struct {
	client influxdb2.Client
	bucket string
	org    string
}

var influxClient influxdb2.Client

func NewInfluxClient(addr, token string) (influxdb2.Client, error) {
	influxClient = influxdb2.NewClient(addr, token)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
	defer cancel()
	// check server is running
	_, err := influxClient.Ready(ctx)
	if err != nil {
		return nil, err
	}
	return influxClient, nil
}

func (db *InfluxDB) GetClient() influxdb2.Client {
	return db.client
}

func (db *InfluxDB) QueryDB(org, query string) *query.FluxRecord {
	if org == "" {
		org = db.org
	}
	result, err := db.client.QueryAPI(org).Query(context.Background(), query)
	if err != nil {
		return nil
	}
	return result.Record()
}

func (db *InfluxDB) Close() {
	db.client.Close()
}

type Test struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
	Ip   string `json:"ip"`
}

func main() {
	// You can generate a Token from the "Tokens Tab" in the UI
	const token = "_ZLr1sejd5fgyDDc2MsUcXR5VPmlD-znRyRzG7Rr-PDnlmBtqR9kkTuUPfCU7em4WOk7sSs6U4YV01JaKBGnpA=="
	const bucket = "test"
	const org = "test"

	client := influxdb2.NewClient("http://127.0.0.1:8086", token)
	// always close client at the end
	defer client.Close()

	//get non-blocking write client
	writeAPI := client.WriteAPI(org, bucket)
	//// write line protocol
	////writeAPI.WriteRecord(fmt.Sprintf("stat,unit=temperature avg=%f,max=%f", 23.5, 45.0))
	////writeAPI.WriteRecord(fmt.Sprintf("stat,unit=temperature avg=%f,max=%f", 22.5, 45.0))
	////// Flush writes
	////writeAPI.Flush()
	ms := make(map[string]interface{})
	for i := 0; i < 100; i++ {
		ms["InUplink"] = float64(i)
		ms["InDownlink"] = float64(i)
		//ms["OutUplink"] = i
		//ms["OutDownlink"] = i
		// write line protocol
		p := write.NewPoint(
			"1",
			map[string]string{
				//"id":       fmt.Sprintf("rack_%v", i%10),
				//"vendor":   "AWS",
				//"hostname": fmt.Sprintf("host_%v", i%100),
			},
			ms,
			time.Now())
		// write asynchronously
		writeAPI.WritePoint(p)
		time.Sleep(time.Second)
	}

	//// Flush writes
	writeAPI.Flush()

	//st,_:= time.Parse("2006-01-02","2021-12-16")
	//
	//dat,_:= time.Parse("2006-01-02","2021-12-17")
	//fmt.Println(st.Unix())

	//t,_ := time.Parse("2006-01-02 15:04:05","2021-12-17 23:20:00 +0000 UTC")
	//start := st.UTC().Unix()
	//fmt.Println(start)
	//stop := dat.UTC().Format("2006-01-02T15:04:05Z")
	//fmt.Println(start,stop)
	//node:= "|> filter(fn: (r) => "
	//for i:=0;i<10 ;i++ {
	//	node += fmt.Sprintf(" r[\"_measurement\"] == \"%d\" or",i)
	//}
	//s := node[:len(node)-2] + " )"
	//query := fmt.Sprintf("from(bucket:\"%v\")|> range(start:%s, stop:%s) " +
	//	s+
	//    "|> filter(fn: (r) => r[\"_field\"] == \"InDownlink\" or r[\"_field\"] == \"InUplink\" or r[\"_field\"] == \"OutDownlink\" or r[\"_field\"] == \"OutUplink\")" +
	//	"|> aggregateWindow(every: 1h, fn: mean)", bucket,"2021-12-17T05:00:00Z","2021-12-18")
	//fmt.Println(query)
	//query := "from(bucket:\"test1\")|> range(start:2021-12-16, stop:2021-12-17) |> filter(fn: (r) => r[\"_field\"] == \"InDownlink\" or r[\"_field\"] == \"InUplink\" or r[\"_field\"] == \"OutDownlink\" or r[\"_field\"] == \"OutUplink\")|> aggregateWindow(every: 1h, fn: mean)"
	////Get query client
	//queryAPI := client.QueryAPI(org)
	//// get QueryTableResult
	//result, err := queryAPI.Query(context.Background(), query)
	//if err == nil {
	//	// Iterate over query response
	//	for result.Next() {
	//		// Notice when group key has changed
	//		//if result.TableChanged() {
	//		//	fmt.Printf("table: %s\n", result.TableMetadata().String())
	//		//}
	//		//Access data
	//		//fmt.Println(result.Record())
	//		fmt.Printf("table: %v ",result.Record().Measurement())
	//	//	fmt.Printf("fild: %v ", result.Record().Field())
	//		fmt.Printf("value: %v\n", result.Record().Values())
	//		//fmt.Println()
	//	}
	//	// check for an error
	//	if result.Err() != nil {
	//		fmt.Printf("query parsing error: %\n", result.Err().Error())
	//	}
	//} else {
	//	panic(err)
	//}
	//
	//

}
